package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.AddressDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Address;
import com.itheima.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service(interfaceClass = AddressService.class)
@Transactional
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressDao addressDao;

    @Override
    public PageResult findAll(QueryPageBean queryPageBean) {
        //取出参数中的数据
        Integer currentPage = queryPageBean.getCurrentPage();//当前页
        Integer pageSize = queryPageBean.getPageSize();//每页显示的条数
        String queryString = queryPageBean.getQueryString();//查询条件
        if (queryString != null && !"".equals(queryString)) {
            currentPage = 1;
        }
        //调用分页插件
        PageHelper.startPage(currentPage, pageSize);
        //调用dao的方法
        Page<Address> page = addressDao.findAll(queryString);
        long total = page.getTotal();//获取总页数
        List<Address> result = page.getResult();//获取所有的地址信息
        for (Address address : result) {
            address.setImg("http://qvg9clowq.hd-bkt.clouddn.com/" + address.getImg());
        }
        return new PageResult(total, result);
    }

    @Override
    public Result add(Address address) {
        //先查询数据库中有没有该地址信息
        String addressName = address.getAddress();
        Integer count = addressDao.findAddress(addressName);
        if(count>0){
            return new Result(false, MessageConstant.ADDRESS_IS_EXISTS);
        }
        //保存数据到数据库中
        addressDao.add(address);
        return new Result(true, MessageConstant.ADD_ADDRESS_SUCCESS);
    }

    @Override
    public void delete(Integer id) {
        //先删除中间表的数据
        addressDao.deleteOA(id);
        //再删除地址表的数据
        addressDao.delete(id);

    }

    @Override
    public Address findById(Integer id) {
        return addressDao.findById(id);
    }

    @Override
    public void update(Address address) {
        addressDao.update(address);
    }
}
